user.admin = liwe.module ( "user.admin", null, "Gestione utenti" );



user.admin._modules = null;
user.admin._groups_on = null;
user.admin._dest_div = "system-content";
user.admin._type = null;
user.admin._curr_uid = null;
user.admin.data_type_busy = false;
user.admin.user_data_busy = false;

user.admin.init = function ( group_admin )
{
	if ( group_admin ) user.admin._groups_on = true;

	var _acts = [
		{ label: 'Utenti', func: function () { user.admin._render_user();} },
		{ label: 'Campi extra', func: function () { user.admin.render_type ( true ); } },
		{ label: 'Sessioni Attive', func: function () { user.admin._render_session(); } }
	];

	if ( group_admin )  _acts.push (  { label : 'Gruppi', func : function () { user.admin._render_group(); } } ); 

	user.admin.register ( _acts );
	user.admin._get_modules ();
	user.admin.valid_events ( [ 'user_create', 'user_cancel', 'modpwd_done', 'modpwd_cancel', 'user-data-updating', 
				'data-type-updating', 'user-data-multiset', 'data-type-multiset' ] ); 

	//EVENTS
	user.admin.addEventListener ( 'user-data-updating', function ( e ) { user.admin.user_data_busy = true; } );
	user.admin.addEventListener ( 'data-type-updating', function ( e ) { user.admin.data_type_busy = true; } );
	user.admin.addEventListener ( 'user_create', user.admin.create_event );
	user.admin.addEventListener ( 'user-data-multiset', user.admin.create_event );
	user.admin.addEventListener ( 'data-type-multiset', function ( e ) { user.admin.data_type_busy = false; user.admin.render_type ( true ); } );
	user.admin.addEventListener ( 'user_cancel', user.admin.cancel_event );
	user.admin.addEventListener ( 'modpwd_done', user.admin.cancel_event );
	user.admin.addEventListener ( 'modpwd_cancel', user.admin.cancel_event );
};
//{{{EVENTS
user.admin.create_event = function ( evt )
{
	var p =  evt [ 'params' ];
	if ( p [ 'module' ] == 'user' )
	{
		user.admin.user_data_busy = false;
		user.admin._user_refresh()
		user.admin.hide_panel ( "form" )	
	};
}
user.admin.cancel_event = function ( evt )
{
	var p =  evt [ 'params' ];
	if ( p [ 'module' ] == 'user' )
	{
		user.admin.hide_panel ( "form" )	
	};
}
//}}}
//{{{COMMON
user.admin.show_panel = function ( name )
{
	var a  = list();
	var type = user.admin._type;
	a.push ( "form", "perms", "group" );
	a.iterate ( function ( panel )
	{
		if ( panel == name ) return;
		var el = $el ( "u_" + type  +  "_panel_" + panel );
		if ( el == null ) return;
		el.style.display = 'none';			 
	} );

	var el = $el ( "u_" + type +  "_panel_" + name );
	el.style.display = "block";
	liwe.fx.fade_in ( el );

};

user.admin.hide_panel = function ( name )
{
	var type = user.admin._type;
	var el = $el ( "u_" + type +  "_panel_" + name );
	liwe.fx.fade_in ( el, function() { el.style.display = "none"; } )

};
user.admin._get_modules = function ( uid )
{
	user.admin.ajax ( { action: "system.ajax.list_all_modules" }, function ( v )
		{
			var opts = list(); 
			var mods = v [ 'modules' ];
			
			liwe.types.to_dict ( mods )

			var mods_name= mods.keys ();
			mods_name.sort ();
			user.admin._modules_str = mods_name.join ( '|' );

			user.admin._modules_perms = mods;

			mods_name.iterate ( function ( val , k  )
					{
						opts.push ( { label : val, value: val } );
					} );
			user.admin._modules = opts;
	} );
};
//}}}
//{{{USER
//{{{user.admin._render_user =  function ()
user.admin._render_user =  function ()
{
	user.admin._am_user_init ( 'u_user_list' );
	user.admin._am_group_init ( 'u_group_list' );
	var _admin_title = String.formatDict ( user.templates [ 'ADMIN_TITLE' ], { '_title' : 'GESTIONE UTENTI' } ); 
	var _dct = { '_admin_title' : _admin_title, '_list_title' : 'Utenti Presenti', '_form_title' : "Inserimento/modifica Utenti" };
	$( user.admin._dest_div, String.formatDict ( user.templates [ 'ADMIN_USER_LAYOUT' ], _dct ) );
	user.admin._user_refresh();		
	user.admin._type = "user";
}
//}}}
//{{{user.admin._user_refresh =  function ( cback )
user.admin._user_refresh =  function ( cback )
{
	user.admin.am_user.show_list ();
	if ( cback ) cback();
};
//}}}
//{{{user.admin._am_user_init = function ( dest_div )
user.admin._am_user_init = function ( dest_div )
{
	if ( user.admin.am_user ) return;
	user.admin.am_user = new AdminManager ( {	'dest_res': dest_div,
							'name' : 'am_user_user',
							'list_action': "user.admin.list_new",
							'del_action' : "user.admin.del_user",
							'filter_form' : user.admin._user_filter_form,
							'filter_form_name' : 'am_user_user_filter',
							'mod_menu_actions': [ { func: "user.admin.show_user_form();", 'class' : 'add' , label: 'Aggiungi Utente' }],
							'glob_menu_actions': [
								{ action_name: 'enabled_all', label: 'Abilita', func: user.admin.enabled },
								{ action_name: 'disabled_all', label: 'Disabilita', func: user.admin.disabled }
							 ] } );
	user.admin.am_user.templates [ 'actions_row_action' ] = user.templates [ 'ADMIN-ROW-ACTION' ];
	user.admin.am_user.templates [ 'glob_single_action' ] = user.templates [ 'ADMIN-GLOB-SINGLE-ACTION'];
	
	user.admin.am_user.set_row_fields ( [ 
											[ "UID", "uid" ], 
											[ "Abilitato", "_enabled" ],
											[ "Login / e-mail", "_txt" ], 
											[ "Data creazione", "_created" ] 
										] );


	user.admin.am_user.set_row_actions ( 
						[ 
							//[ user.templates [ 'ADMIN-USER-ACTION-MODPWD' ], "modify_pwd" ],
							[ user.templates [ 'ADMIN-USER-ACTION-SETPERMS' ], "set_perms" ],
							[ user.templates [ 'ADMIN-USER-ACTION-SETGROUP' ], "set_group" ]
						] );

	//user.admin.am_user.cbacks [ 'modify_pwd' ] = function ( id ) { user.admin._modify_pwd ( id ); };
	user.admin.am_user.cbacks [ 'set_perms' ] = function ( id ) { user.admin._user_set_perms ( id ); };
	user.admin.am_user.cbacks [ 'set_group' ] = function ( id ) { user.admin._user_set_group ( id ); };

	user.admin.am_user.cbacks [ 'row_manip' ] = user.admin._rwman_user;
	user.admin.am_user.cbacks [ 'del_item' ]  = function ( id ) { user.admin.del_user ( id ); };
	user.admin.am_user.cbacks [ 'edit_item' ]  = function ( id ) { user.admin.edit_user ( id ); };

	user.admin.am_user.cbacks [ 'row_manip' ] = user.admin.rwman_user;
};
//}}}
//{{{user.admin.rwman_user = function ( ds, row )
user.admin.rwman_user = function ( ds, row )
{
	row [ '_id' ] = row [ 'uid' ];
	row [ '_txt' ] = String.formatDict ( user.templates [ 'ADMIN_USER_COLUMN' ] , row );//'<b>' + row [ 'login' ] + '</b> ' + row [ 'email' ];

	row [ '_created' ] = '&nbsp;';
	if ( row.get ( 'created' ) )
		row [ '_created' ] = liwe.utils.date2str ( row [ 'created' ], 1 );

	var _switch =  [ 'off', 'on' ];
	var _visible = row [ 'enabled' ];
	row [ '_enabled' ] = String.formatDict ( user.templates [ 'ADMIN_ON_OFF'], { '_class' : _switch[ _visible ] , '_id' : row [ '_id' ] } );
};
//}}}
//{{{user.admin._user_filter_form = function ( dest_div )
user.admin._user_filter_form = function ( dest_div )
{
	var f = new liwe.form.instance ( 'am_user_user_filter' );
	f.text ( { label : 'User', name: 'login', nonl : true } );
	f.email ( { label : 'Email', name: 'email', nonl : true } );
	f.checkbox ( { label : 'Abilitato', name: 'enabled', value : 1 , checked : true } );	
	f.button ( { value: "Filtra", "class": 'green',  onclick: "user.admin._user_filter_apply()", nonl: true } );
	f.button ( { value: 'Reset', 'class' : 'yellow', onclick: function ( f ) { f.clear (); } } );
	f.set ( dest_div );
};
//}}}
//{{{user.admin._user_filter_apply = function ()
user.admin._user_filter_apply = function ()
{
	user.admin.am_user.search_start ();
};
//}}}
//{{{USER ENEBLE DISABLE FUNCTIONS
user.admin.enabled = function ( uids )
{
	if ( ! uids ) return;

	user.admin._set_enabled ( uids, 1 );
};

user.admin.disabled = function ( uids )
{
	if ( ! uids ) return;

	user.admin._set_enabled ( uids );
};

user.admin._set_enabled = function ( ids, en )
{
	if ( ! en ) en = 0;

	user.admin.ajax ( { action: 'user.admin.set_enabled', uids: ids.join ( "|" ), enabled: en }, function ( v )
	{
		user.admin.am_user.show_list ();
	} );
};

user.admin.set_user_enable = function ( el, uid  )
{
	var enable = 1;
	var new_class = "on"
	var old_class = "off"
	if ( liwe.dom.has_class ( el, "on" ) ) 
	{
		enable = 0;
		new_class = "off";
		old_class = "on";
	}
	var post = { 'action' : 'user.admin.set_enabled',
				 'uids' : uid, 
				 'enable' : enable }
	user.ajax ( post , function ()
	{
		var  el_onoff = $el ( "visible_" + uid );
		liwe.dom.del_class ( el_onoff, old_class );
		liwe.dom.add_class ( el_onoff, new_class );		
	} );

}
//}}}
//{{{user.admin.edit_user = function ( id )
user.admin.edit_user = function ( id )
{
	user.admin.ajax ( { action: "user.admin.get", uid: id }, function ( v )
	{
		user.admin.show_user_form (  v [ 'user' ]  ) //, true ); Unificate login e password in un solo form
	});
};
//}}}
//{{{user.admin.del_user = function ( dest_div, id )
user.admin.del_user = function ( id )
{
	if ( ! id ) return;

	if ( confirm ( "Sei sicuro di voler eliminare questo utente?" ) )
	{
		user.admin.ajax ( { action: "user.admin.delete", ids: id }, function ( v ) 
		{
			user.admin.am_user.show_list ();
		} );
	}
};
//}}}
//{{{user.admin.show_user_form = function ( dct , edit )
user.admin.show_user_form = function ( dct , edit )
{
	if ( ! dct ) dct = {};
	var uid = dct.get ( 'uid', '' )
	var title =  uid ? "Modifica utente [ " +  uid  + " ]" : "Creazione nuovo utente" ;
	$ ( "u_user_form_title", title );
	user.admin.render_user_form ( dct, 'u_user_form', edit );
	user.admin.show_panel ( "form" );
}
//}}}
//{{{user.admin.render_user_form = function ( data, dest_div, edit )
user.admin.render_user_form = function ( data, dest_div, edit )
{
	if ( ! data ) data = {};
	module = data.get  ( 'module' , 'user' );

	if ( ! user.data_type_list )
	{	
		user.user_data_type_list ( function () { user.admin.render_user_form ( data, dest_div, edit ); } );
		return;
	}
	var uid = data.get ( 'uid', -1 );
	user.admin.user_data_get ( uid, null, function ( user_data )
	{	
		user.admin._render_user_form ( data, dest_div, user_data )
	} );
}

user.admin._render_user_form = function ( data, dest_div, user_data )
{
	var edit = null;
	var uid = data.get ( "uid", -1 );
	user.admin.tmp_user_data = user_data;
	var f = new liwe.form5.instance ( "user-frm" );
	f.add ( "hidden", "uid", { "value" : uid } ); 
	f.add ( "hidden", "module", { "value" : module } );
	f.add ( "hidden", "dest_div", { "value" : dest_div } );
	f.add ( "input", "login", { "value" : data.get ( "login", "" ), "label" : "User", "mandatory" : true } );
	f.add ( "input", "email", { "value" : data.get ( "email", "" ), "label" : "Email", "mandatory" : true } );
	if ( ! edit )
	{
		f.add ( "password", "pwd", { "label": "Password" } );
		f.add ( "password", "pwd2", { "label": "Password ( conferma )" } );
		f.add ( "hidden", "edit", { "value": 0 } );
	}else{
		f.add ( "hidden", "edit", { "value": 1 } );
	}
	user.add_data_fields ( f, user_data, data )
	f.add ( "select", "extra_field_sel", { "options": user.data_type_opts, 
		"onchange": "user.admin.add_new_data_field ( 'user-frm' );", "label": "Nuovo campo" } ); 
	f.add ( "checkbox", "enabled", { "value" : 1, "label": "Abilitato", "checked":  data.get ( "enabled", 0 ) } );
	f.add ( "button", "btn_save", { "class" : "green", "value": "Salva", "onclick": "user.admin.create_done()" , "nonl" : true } );
	f.add ( "button", "cancel", { "value": "Annulla", "class" : "grey", "onclick" : "user.admin.create_cancel()" } );
	f.set ( dest_div );
};
//}}}		
//{{{user.admin.create_done = function ()
user.admin.create_done = function ()
{
	//var f = liwe.form.get ( "user-frm" );
	var f = liwe.form5.get ( "user-frm" );

	if ( ! f.check () ) return;

	var dct = f.get_values ();
	dct [ 'action' ] = 'user.admin.create';

	if ( dct [ 'pwd' ] != dct [ 'pwd2' ] )
	{
		alert ( "La password non corrisponde" );
		// f.set_focus ( "pwd" );
		return;
	}

	user.admin.ajax ( dct, function ( v )
	{
		dct [ 'uid' ] = v [ 'uid' ];
		user.admin.dispatchEvent ( "user_create", null, dct );
		user.admin.user_data_set_done ( 'user-frm', dct );
	} );
};
//}}}

//{{{user.admin.create_cancel = function ()
user.admin.create_cancel = function ()
{
	//var f = liwe.form.get ( "user-frm" );
	var f = liwe.form5.get ( "user-frm" );
	var dct = f.get_values ();
	user.admin.dispatchEvent ( "user_cancel", null, dct );
}
//}}}
//{{{user.admin._modify_pwd = function ( uid )
user.admin._modify_pwd = function ( uid )
{
	$ ( "u_user_form_title", "Modifica Password [ " + uid + " ]" );

	user.admin.render_modify_pwd_form  ( uid,  'u_user_form', 'user' )
	user.admin.show_panel ( "form" );
};
//}}}
user.admin.render_modify_pwd_form = function ( uid, dest_div, module )
{
	var f = new liwe.form.instance ( "user-change-pwd-frm" );

	f.hidden ( 'uid', uid );
	f.hidden ( 'action', "user.admin.change_pwd" );
	f.hidden ( 'module' , module )

	f.password ( { name: 'pwd', label: 'Password', mandatory: true } );
	f.password ( { name: 'pwd2', label: 'Password (conferma)', mandatory: true } );
	f.button ( { name: 'btn_save','class' : 'green', value: 'Salva', onclick: "user.admin.change_pwd_done()", nonl : true } );
	f.button ( { value: 'Annulla', 'class' : "grey", onclick : "user.admin.change_pwd_cancel()", colspan : 2 } );

	f.set ( dest_div );
	
} 
//{{{user.admin.change_pwd_done = function ()
user.admin.change_pwd_done = function ()
{
	var f = liwe.form.get ( "user-change-pwd-frm" );

	if ( ! f.check () ) return;

	var dct = f.get_values ();

	if ( dct [ 'pwd' ] != dct [ 'pwd2' ] )
	{
		alert ( "La password non corrisponde" );
		f.set_focus ( "pwd" );
		return;
	}

	user.admin.ajax ( dct, function ( v )
	{
		user.admin.dispatchEvent ( "modpwd_done", null, dct );
	} );

};
//}}}
user.admin.change_pwd_cancel = function ()
{
	var f = liwe.form.get ( "user-change-pwd-frm" );
	var dct = f.get_values ();
	user.admin.dispatchEvent ( "modpwd_cancel", null, dct );
	
}
//{{{user.admin._user_set_perms = function ( uid )
user.admin._user_set_perms = function ( uid )
{
	var row_uid = $el ( "uid_" + uid );
	$( 'u_user_perms_title',  "Modifica permessi [ " + row_uid.innerHTML + " ]" ) ;

	user.admin._main_form_perms ( uid);
	user.admin.show_panel ( "perms" );
};
//}}}
user.admin._user_set_group = function ( uid )
{
	var row_uid = $el ( "uid_" + uid );
	$( 'u_user_group_title',  "Modifica Gruppi [ " + row_uid.innerHTML + " ]" ) ;

	user.admin._set_user_panel ( uid );

	user.admin.show_panel ( "group" );
};
user.admin._set_user_panel = function ( uid )
{
	user.admin._curr_uid = uid; 
	var pan_div = "u_user_group";
	var attrs = {
					head_left: 'Utenti non nel gruppo',
					head_right: 'Utenti nel gruppo'
				};

	var post = { 'action' : 'user.group_admin.get_user_group', 'uid' : uid }
	user.admin.ajax ( post , function ( resp )
	{
		var section = dict() 
		var for_iterate = list();
		for_iterate.push ( "ingroup", "notingroup" );
		for_iterate.iterate ( function ( key )
		{
			section [ key ] = {};
			var sect = resp [ key ];
			if ( sect == null ) return
			liwe.types.to_dict ( sect );

			var items = list();
			sect.iterate ( function ( item ) 
			{
				items.push ( { id : item [ 'gid' ], name : item [ 'name' ], title : item [ 'descr' ] } );
			} );
			
			section [ key ] = items;			
		} );	
		
		var pan = new WWL.panels ( pan_div , attrs );

		pan.set_cbacks ( 'done', user.admin.save_user_group );
		pan.render ( pan_div ); 
		pan.populate ( section  [ 'notingroup' ] , section [ 'ingroup' ] );
	} );
};


user.admin.save_user_group = function ( groups_lst )
{
	var uid = user.admin._curr_uid;
	if ( ! uid ) return;
	var vals = {
			action : 'user.group_admin.save_user_group',
			uid : uid
			};
			
	gids_lst = groups_lst [ 'group_right' ];
	if ( gids_lst.length < 1 )
	{
		 vals = { action : 'user.group_admin.empty_group_user', gid : uid , mode :user.admin._type };
	}
	vals [ 'gids' ] = gids_lst;
	user.admin.ajax ( vals, function ( data ) 
				{
					liwe.utils.notifier.show ( 'Modifiche gruppo utente salvate', '', 1500 );
				} );

};
//}}}
//}}}

//{{{GROUPS
//{{{user.admin._render_group =  function ()
user.admin._render_group =  function ()
{
		var _admin_title = String.formatDict ( user.templates [ 'ADMIN_TITLE' ], { '_title' : 'GESTIONE GRUPPI' } ); 
		var _dct = { '_admin_title' : _admin_title, '_list_title' : 'Gruppi Presenti', '_form_title' : "Inserimento/modifica Gruppi" };
		$( user.admin._dest_div, String.formatDict ( user.templates [ 'ADMIN_GROUP_LAYOUT' ], _dct ) );
		user.admin._type = "group";
		user.admin._group_refresh();		
}
//}}}
//{{{user.admin._group_refresh =  function ( cback )
user.admin._group_refresh =  function ( cback )
{
	user.admin.am_group.show_list ();
	if ( cback ) cback();
};
//}}}
//{{{user.admin._am_group_init = function ( dest_div )
user.admin._am_group_init = function ( dest_div )
{
	if ( user.admin.am_group ) return;

	user.admin.am_group = new AdminManager ( {	'dest_res': dest_div,
												'name' : 'am_user_group',
												'list_action': "user.group_admin.list",
												'del_action': 'user.group_admin.delete',
												'glob_menu_actions': [], 
												'mod_menu_actions': [ { func: "user.admin._group_form();", 'class' : 'add' , label: 'Aggiungi gruppo' } ]
											  } );

	user.admin.am_group.set_row_fields ( [ 
											[ "GID", "gid" ], 
											[ "Gruppo", "_gid_name" ], 
											[ "Descrizione", "descr" ] 
									     ] );

	user.admin.am_group.templates [ 'actions_row_action' ] = user.templates [ 'ADMIN-ROW-ACTION' ];
	user.admin.am_group.templates [ 'glob_single_action' ] = user.templates [ 'ADMIN-GLOB-SINGLE-ACTION'];

	user.admin.am_group.set_row_actions ([ [ user.templates [ 'ADMIN-USER-ACTION-SETPERMS' ], "set_perms" ] ]);

	user.admin.am_group.cbacks [ 'row_manip' ] = user.admin.rwman_group;

	user.admin.am_group.cbacks [ 'del_item' ]  = function ( id ) { user.admin.del_group ( id ); };
	user.admin.am_group.cbacks [ 'edit_item' ]  = function ( id ) { user.admin.edit_group ( id ); };

	user.admin.am_group.cbacks [ 'set_perms' ] = function ( id ) { user.admin._group_set_perms ( id ); };

}
//}}}
//{{{user.admin.rwman_group = function ( ds, row )
user.admin.rwman_group = function ( ds, row )
{
	row [ '_id' ] = row [ 'gid' ];
	row [ 'id' ] = row [ 'gid' ];
	row [ '_gid_name' ] = String.formatDict ( user.templates [ 'ADMIN_GROUP_COLUMN' ] , row );
};
//}}}
//{{{user.admin._group_form = function ( dct )
user.admin._group_form = function ( dct )
{
	if ( ! dct ) dct = {};

	var gid = dct.get ( 'gid', '' )
	var title =  gid ? "Modifica gruppo [ " +  gid  + " ]" : "Creazione nuovo gruppo" ;
	$ ( "u_group_form_title", title );

	var f = new liwe.form.instance ( "group-frm" );

	f.hidden ( 'gid', gid );
	f.hidden ( 'action', "user.group_admin.create" );

	f.text ( { name: 'name', label: 'Nome', mandatory: true, value: dct.get ( 'name', '' ) } );
	f.text ( { name: 'descr', label: 'Descrizione', value: dct.get ( 'descr', '' ) } );

	f.button ( { name: 'btn_save','class' : 'green', value: 'Salva', onclick: "group.admin.create_done()" } );

	f.set ( 'u_group_form' );
	user.admin.show_panel ( "form" );
};
//}}}
//{{{user.admin.edit_group = function ( id )
user.admin.edit_group = function ( id )
{
	user.admin.ajax ( { action: "user.group_admin.get", gid: id }, function ( v )
	{
		user.admin._group_form (  v [ 'group' ] );
	});
};
//}}}

user.admin._group_set_perms = function ( gid )
{
	var row_uid = $el ( "gid_" + gid );
	$( 'u_group_perms_title',  "Modifica permessi [ " + row_uid.innerHTML + " ]" ) ;

	user.admin._main_form_perms ( gid);
	
	user.admin.show_panel ( "perms" );
};
//}}}

//{{{PERMS
user.admin._main_form_perms = function ( id )
{
	var type = user.admin._type;
	var post = { action : 'system.ajax.module_get_all_perms', 
				uid : id,
				perms_type: user.admin._type,
				module_names: user.admin._modules_str
			 };	

	var add_form_perms = function ( perm, name, data )
	{
		var f_name = "form_set_perms_" + name ;
		var f = new liwe.form.instance ( f_name );
		f.hidden ( "uid", id );
		perm.iterate ( function ( v )
		{
			var val = 0;
			if ( data.indexOf ( v [ 'value' ] ) != -1  ) val = 1 ;
			f.checkbox ( { name: 'perm.' + v [ 'value' ], label: v [ 'label' ], value: v [ 'value' ], checked: val  } );	
		} );
		f.set ( "form_" + name  + "_cnt" );
	};

	var perms_div = $el ( "u_" + type  + "_perms_forms" );
	perms_div.innerHTML = "";

	user.admin.ajax ( post, function ( resp )
	{
		var perms = resp.perms;
		liwe.types.to_dict ( perms );

		user.admin._modules.iterate ( function ( v )
		{
			var module_name = v [ 'value' ]
			var module_perms = user.admin._modules_perms [ module_name ];
			if ( module_perms.count() == 0 ) return;

			var html =  String.formatDict ( user.templates [ 'ADMIN_MODULE_PERMS' ] , v ) ; 
			perms_div.innerHTML = perms_div.innerHTML + html;

			var data = perms [ module_name ];
		
			add_form_perms ( module_perms, module_name , data );
		} ) ;
		window.scrollTo ( 0,0 );
	} );
};

user.admin.save_perms = function ()
{
    user.admin._modules_perms.iterate ( function ( v, m_name )
        {

            f = liwe.form.get ( 'form_set_perms_' + m_name );
			if ( typeof ( f ) == "undefined" ) return;		
	
			var values = f.get_values ();
			liwe.types.to_dict ( values )
			//var keys = v.keys (), l = k.length, t;

			var res = list ();

			values.iterate ( function ( v,k ) 
			{ 
				if ( v == false || ! k.startsWith ( "perm." ) ) return;
				res.push ( k.slice ( 5 )  ); 
			} );


			var vals = { 
					action: "system.admin.module_set_perms",
					module_name: m_name,
					uid: values.get ( 'uid', 0 ),
					perms: ':'.join ( res ),
					perms_type: user.admin._type
					};	

			liwe.AJAX.add ( 'multi-user-perms', liwe.AJAX.url, vals ); 

        } );
    	liwe.AJAX.start ( 'multi-user-perms', function ( resp ) 
		{
			liwe.utils.notifier.show ( 'Modifiche permessi  salvate', '', 1500 );
			user.admin.hide_panel ( "perms");
		} );
};

user.admin.check_all_perms = function ( el, m_name )
{
	f = liwe.form.get ( 'form_set_perms_' + m_name );
	var values = f.get_values();
	liwe.types.to_dict ( values );
	values.iterate ( function ( v , k )
	{
		if ( ! k.startsWith ( "perm." ) ) return;
		f.set_value ( k, el.checked );
	} );
	
}
//}}}

//{{{SESSION

user.admin._render_session =  function ()
{
	user.admin._am_session_init ( 'u_session_list' );
	$( user.admin._dest_div, user.templates [ 'ADMIN_SESSION_LAYOUT' ] );
	user.admin._session_list_refresh();		
};

user.admin._session_list_refresh =  function ( cback )
{
	user.admin.am_session.show_list ();
	if ( cback ) cback();
};
user.admin._am_session_init = function ( dest_div )
{
	if ( user.admin.am_session ) return;

	user.admin.am_session = new AdminManager ( {	'dest_res': dest_div,
												'name' : 'am_user_session',
												'list_action': "user.admin.list_user_session",
												'del_action': 'user.admin.delete_user_session',
												'filter_form' : user.admin._session_filter_form,
												'filter_form_name' : 'am_user_session_filter'
											  } );

	user.admin.am_session.set_row_fields ( [ 
											[ "UID", "uid" ], 
											[ "User", "login" ], 
											[ "e-Mail", "email" ],
											[ "Ultimo Accesso", "_lastlog" ]
									     ] );

	user.admin.am_session.templates [ "actions_head" ] = '<table class="adminman_actions" border="0" width="100%"><tr>';
	user.admin.am_session.templates [ "edit_obj" ] = "";

	user.admin.am_session.cbacks [ 'row_manip' ] = user.admin.rwman_session
	user.admin.am_session.cbacks [ 'del_item' ]  = function ( id ) { user.admin.del_user_session ( id ); };
};
user.admin.rwman_session = function ( ds, row )
{
	row [ '_id' ] = row [ 'session_id' ];
	row [ "_lastlog" ] = Date.formatted ( "%d/%m/%Y  %h:%M ", row [ 'lastlog' ] );
};
user.admin._session_filter_form = function ( dest_div )
{
	var f = new liwe.form.instance ( 'am_user_session_filter' );
	f.number ( { label : 'UID' , name : 'uid', nonl : true } );
	f.text ( { label : 'User', name: 'login', nonl : true } );
	f.email ( { label : 'Email', name: 'email', nonl : true } );
	f.button ( { value: "Filtra", "class": 'green',  onclick: "user.admin.am_session.search_start()", nonl: true } );
	f.button ( { value: 'Reset', 'class' : 'yellow', onclick: function ( f ) { f.clear (); } } );
	f.set ( dest_div );
};
user.admin.del_user_session = function ( ids )
{
	if ( ! confirm ( 'Confermi la cancellazione?' ) ) return;
        var _post = { 'action' : 'user.admin.del_user_session', 'ids' : ids };
        user.admin.ajax ( _post , function ()
        {
		user.admin._session_list_refresh ( function () 
		{
			liwe.utils.notifier.show ( 'Sessione Utente Eliminata correttamente', 'info', 2000)
		});	
        });
}; 
//}}}

/* ----------------- USER DATA TYPE ---------------------*//*{{{*/

user.admin.render_type =  function ( reload )
{
	$( user.admin._dest_div, user.templates [ 'ADMIN_TYPE_LAYOUT' ] );
	user.admin.data_type_refresh ( reload );		
};

user.admin.data_type_refresh = function ( reload )
{
	user.data_type_list = null;
	if ( reload ) user.admin.data_type_form ();
};

user.admin.data_type_form = function ( dest_div )/*{{{*/
{
	dest_div = dest_div || 'u_type_list';
	if ( ! user.data_type_list )
	{	
		user.user_data_type_list ( function () { user.admin.data_type_form ( dest_div ); } );
		return;
	}
	var last_id, f = new liwe.form5.instance ( 'data-type-form' );
	user.data_type_list.iterate ( function ( data, idx )
	{
		f.add ( "input", "type_" + idx, { "label": data.name, "value" : data.name, "data-idtype" : data.id_data_type } );
		last_id = idx;
	} );
	f.add ( "input", "type_" + last_id + 1, { "label": "Nuovo campo", "value" : "", "data-idtype" : 0 } );
	f.add ( "button", "update", { "value": "Aggiorna", "onclick": "user.admin.data_type_multiset ( 'data-type-form' );", "class": "green" } );
	f.set ( dest_div );
};/*}}}*/

user.admin.data_type_multiset = function ( form_id )/*{{{*/
{
	if ( user.admin.data_type_busy ) { alert ( 'Aggiornamento in corso. Attendere prego.' ); return };
	var f = liwe.form5.get ( form_id );
	if ( ! f ) return;
	var fields = f.get_values ();
	var type_list = list ();
	fields.iterate ( function ( val, field )
	{
		var vals; 
		var tmp = $( form_id + '-' + field );
		//check if is a valid input field
		if ( ! tmp || ! ( tmp.dataset && tmp.dataset.idtype ) ) return;
		var data = tmp.dataset;
		if ( ! val || val == '' )
		{	
			vals = { 'action' : 'user.admin.user_data_type_del', 'id_data_type': data.idtype }; 
		} else {
			vals = {
				'action'	: 'user.admin.user_data_type_set',
				'id_data_type'	: data.idtype,
				'name'		: val
				};
		}	
		type_list.push ( { 'name': val, 'id_data_type' : data.idtype } );
		liwe.AJAX.add ( 'data-type-multiset', liwe.AJAX.url, vals );
	} );
	user.admin.dispatchEvent ( 'data-type-updating', null, { 'type_list' : type_list } );
	liwe.AJAX.start ( 'data-type-multiset', function () { user.admin.dispatchEvent ( 'data-type-multiset', null, { 'type_list' : type_list } ); } ); 
	
};/*}}}*/

user.admin.data_type_set = function ( name, id_type )/*{{{*/
{
	var vals = { 	'action' : 'user.admin.data_type_set', 
			'name' : name,
			'id_data_type' : id_type 
			};
	user.admin.ajax ( vals, function ( data ) 
	{
		user.user_data_type_list ();
		var dct = { 'type_id' : data.get ( 'type_id', 0 ), 'name' : name };
		user.admin.dispatchEvent ( 'data-type-set', null, dct ); 
	} );
};/*}}}*/

user.admin.data_type_del = function ( id_data_type )/*{{{*/
{
	if ( ! user_data_type ) return;
	var vals = {
		'action': 'user.admin.data_type_del',
		'user_data_type': user_data_type
		};
	user.admin.ajax ( vals, function ( res )
	{
		user.user_data_type_list ( function () 
		{ 
			user.admin.dispatchEvent ( 'user-data-type-del', null, { 'id_data_type': id_data_type } );
		} );
	} );
};/*}}}*//*}}}*/

/* ----------------- USER DATA ---------------------*/
user.admin.user_data_set_done = function  ( form_id, form_fields )/*{{{*/
{
	if ( ! form_fields )
	{
		var f = liwe.form5.get ( form_id );
		form_fields = f.get_values ();
	}
	var match = 'user_data_field';
	var uid = form_fields.get ( 'uid', -1 );
	var data_list = list ();
	form_fields.iterate ( function ( val, field )
	{
		if ( field.indexOf ( match ) == -1 ) return;
		var tmp = $( form_id + '-' + field );
		if ( ! tmp ) return;
		var data = tmp.dataset;
		data_list.push ( { 	
			'id_data_type': data [ 'idtype' ],
			'id_user_data': data [ 'iduser' ],
			'value': val
			} );
	} ); 
	user.admin.tmp_user_data = null;
	user.admin.user_data_multiset ( uid, data_list ); 
};/*}}}*/

user.admin.add_new_data_field = function ( form_id, dest_div )/*{{{*/
{
	var f = liwe.form5.get ( form_id );
	var vals = f.get_values ();
	dest_div = dest_div || vals [ 'dest_div' ];
	var id_type = vals [ 'extra_field_sel' ];
	if ( id_type == 0 ) return;
	var type = user.data_type_list [ id_type ].get ( 'name', '' );
	var user_data = user.admin.tmp_user_data; 
	user_data.push ( { 'id_data_type' : id_type, 'name': type } );
	user.admin._render_user_form ( vals, dest_div, user_data );
};/*}}}*/

user.admin.sel_data_field = function ( f, uid, dest_div )/*{{{*/
{
	if ( ! user.data_type_list )
	{	
		user.user_data_type_list ( function () { user.admin.sel_data_field ( f, uid, dest_div ); } );
		return;
	}
	var frm = new liwe.form5.instance ( 'add-data-field-' + uid );
	frm.add ( 'select' , 'add-data-field', { 'options' : user.data_type_opts, 'nonl' : true } );
	frm.add ( 'button' , 'data-btn', { 'value' : 'Aggiorna', 'onclick' : 'user.admin.add_data_field ( \'' + f.name + '\' ); return;'  } );
	if ( ! dest_div ) return frm.to_string ();
	frm.set ( dest_div );
};/*}}}*/

user.admin.user_data_get = function ( uid, id_data_type, cback )/*{{{*/
{
	var vals = {	'action'	: 'user.admin.user_data_get',
			'id_data_type'	: id_data_type,
			'uid'		: uid
			};
	user.ajax ( vals,  function ( data ) 
	{ 
		var user_data = data.get ( 'user_data' );
		user.dispatchEvent ( 'user-data-get', null, { 'user_data' : user_data } );
		if ( cback ) cback ( user_data ); 
	} );
};/*}}}*/

user.admin.user_data_set = function ( uid, id_data_type, value, id_user_data )/*{{{*/
{
	var vals = {
		'action'	: 'user.admin.user_data_set',
		'uid'		: uid,
		'id_data_type'	: id_data_type,
		'value'		: value,
		'id_user_data'	: id_user_data
		};
	user.admin.ajax ( vals, function ( data )
	{
		delete vals.action;
		vals [ 'id_user_data' ] = data.get ( 'id_user_data' )
		user.admin.dispatchEvent ( 'user-data-set', null, vals );
	} );
};/*}}}*/
/*
UPDATE/DELETE multiple user_data fields
	- data_list: [	{
			'id_data_type':	data type ( optional when delete ) 
			'id_user_data': id user data ( needed for update, optional: delete/insert )
			'value': 	user data value ( if empty the field will be deleted )
			}	]
*/
user.admin.user_data_multiset = function ( uid, data_list )/*{{{*/
{
	if ( user.admin.user_data_busy ) { alert ( 'Aggiornamento in corso. Attendere prego.' ); return };
	data_list.iterate ( function ( val )
	{
		var vals = {};
		var value = val.get ( 'value' );
		if ( ! value || value == '' )
		{
			// if no value user data will be deleted
			vals = { 'action': 'user.admin.user_data_del', 'id_user_data'  : val.get ( 'id_user_data' ) };	
		} else {
			// otherwise it will be added or updated
			vals = { 
				'action'	: 'user.admin.user_data_set',
				'uid'		: uid,
				'id_data_type'	: val.get ( 'id_data_type' ),
				'id_user_data'	: val.get ( 'id_user_data' ),
				'value'		: val.get ( 'value' )
			};
		}
		
		liwe.AJAX.add ( 'user_data', liwe.AJAX.url, vals );
	} );
	user.admin.dispatchEvent ( 'user-data-updating', null, { 'data_list' : data_list } );
	liwe.AJAX.start ( 'user_data', function () { user.admin.dispatchEvent ( 'user-data-multiset', null, { 'uid' : uid } ); } ); 
};/*}}}*/
